var express = require('express');
const path = require('path');
var getPixels = require("get-pixels")
var { mLength, BANNELMAP, COLORLIST } = require('../constant2.js');
const app = express()
const server = require('http').Server(app)

const DEFAULT_PORT = 80


const IMGURL = "../img/" + "ce06405a771974da8bf9399632f2f663.jpg"
const maxWidth = 800
const bannelLength = 156		//400 / 256 / 156
const bannelNum = BANNELMAP[bannelLength]		
var tableDatas = [];
var array1 = [];
var array2 = [];
var gridDivHTML = ""


var flag1 = false // 横向是否调整适应背板填满
var flag2 = false // 是否显示真实颜色
var flag3 = true // 输出grid图
var flag4 = true // 输出array
var realWidth = flag1 ? Math.floor(maxWidth/bannelLength) * bannelLength : maxWidth
var realHeight = 0
var columns = Math.round(realWidth/mLength)
var rows = 0

getImgColorList()

function getImgColorList(){
    getPixels( IMGURL , function(err, pixels) {
        if(err) {
          return console.log("Bad image path")
        }
        var [ imgWidth, imgHeight ] = pixels.shape.slice()
        realHeight = realWidth * imgHeight / imgWidth
        rows = Math.round(realHeight/mLength)
        for (let j = 0; j < rows; j++) {
            for (let i = 0; i < columns; i++) {
                var x = Math.round(i * imgWidth/columns), y = Math.round(j * imgHeight/rows)
                if(x>imgWidth) x = imgWidth
                if(y>imgHeight) y = imgHeight
                var rgb = `rgb(${pixels.get(x,y,0)},${pixels.get(x,y,1)},${pixels.get(x,y,2)})`
                var index = j * columns + i 
                tableDatas[index] = {rgb}
                if(flag2){
                }else{
                    tableDatas[index] = mapListColor(rgb)
                }
                if(flag3){
                    gridDivHTML+=`<div style="background:${tableDatas[index].rgb}"></div>`;
                }
                if(flag4){
                    makeArray(i, j, tableDatas[index].name, tableDatas[index].rgb)
                }
            }
        }
        getHTML()
    })
}
function mapListColor(rgb_origin){
    var rgb_Arr = rgb_origin.split(",").map((v)=>v.replace(/[^0-9]/ig,""))
    var minVal = 3000000, rgb = "", name = "";
    for (let j = 0; j < COLORLIST.length; j++) {
        var arr = COLORLIST[j].rgb.split(",").map((v)=>v.replace(/[^0-9]/ig,""))
        var value = (arr[0]-rgb_Arr[0])*(arr[0]-rgb_Arr[0]) + 
                    (arr[1]-rgb_Arr[1])*(arr[1]-rgb_Arr[1]) +
                    (arr[2]-rgb_Arr[2])*(arr[2]-rgb_Arr[2])
        if( value < minVal ){
            rgb = COLORLIST[j].rgb, minVal = value, name = COLORLIST[j].name
        }
    }
    return {rgb, name}
}
function makeArray(arr_x, arr_y, name, rgb){
    // if(!array1[arr_y]){
    //     array1[arr_y] = []
    // }
    // array1[arr_y][arr_x] = {name,rgb}

    var block_y = Math.floor(arr_y/bannelNum), block_x = Math.floor(arr_x/bannelNum) 
    var block_num = block_y*Math.ceil(columns/bannelNum) + block_x
    var arr_offset_x = arr_x%bannelNum, 
        arr_offset_y = arr_y%bannelNum 
    if(!array2[block_num]){
        array2[block_num] = []
    }
    if(!array2[block_num][arr_offset_y]){
        array2[block_num][arr_offset_y] = []
    }
    array2[block_num][arr_offset_y][arr_offset_x] = {name,rgb}
}
function getHTML(){
    app.use(function (req, res, next) {  
        const regArr = [ /^\/img/, /.ico$/ ]
        if(regArr.some( v=> v.test(req.url) )){
            return next()       //静态资源，都走下一个中间件
        }
        var tableHTML = array2.map((arr2,i)=>
            `<table>${arr2.map(arr1=>
                `<tr>${arr1.map(v=>
                    `<td style="background:${v.rgb}"><div>${v.name}</div></td>`).join("")}
                </tr>`).join("")}
            </table>`).join("")
        res.write(`<!DOCTYPE html>
        <html lang="en">
            <head>
                <meta charset="utf-8">
                <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
                <meta name="theme-color" content="#000000">
                <title></title>
                <style>
                    body{background: #f7c376;color: white;margin: 0px;width: 5000px;height: 5000px;}
                    .container{display: grid;}
                    table{border-collapse:collapse;}
                    table td{border:1px solid black;text-align: center;}
                    table td div{width: 30px;line-height: 30px;}
                </style>
            </head>
            <body>
                <img id="img" src="${IMGURL}" width="${realWidth}">
                <div id="container" class="container" style="background:url(${IMGURL}) no-repeat;background-size:${realWidth}px;
                        grid-template-columns:repeat(${columns}, ${mLength}px);grid-template-rows:repeat(${rows}, ${mLength}px)">
                    ${gridDivHTML}
                </div>
                ${tableHTML}
            </body>
        </html>`)
        res.end()
    })
    //      虚拟路径                          当前文件真实路径  图片目录
    app.use( '/img', express.static(path.join(__dirname, '../img')))    //静态资源映射
    server.listen(DEFAULT_PORT, function () {
        console.log('node app start at port '+DEFAULT_PORT)
    })
}

